package ohtu;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

public class ObjectIOHandler {

	private static FileOutputStream f_out;
	private static ObjectOutputStream o_out;
	private static FileInputStream f_in;
	private static ObjectInputStream o_in;
	private static File f;
	private static Object e;

	public ObjectIOHandler() { e = null; }

	public static Object load(String name) {
		f = new File(name);

		try {
			f_in = new FileInputStream(f);
			o_in = new ObjectInputStream(f_in);

			try { e = o_in.readObject(); }
			catch (ClassNotFoundException ex) { System.out.println("Class not found"); }

			f_in.close();
		}
		catch (FileNotFoundException ex1) {
			System.out.println("File " + name + " not found.");
		}
		catch (IOException ex2) {
			System.out.println("I/O Error occured.");
		}

		return e;
	}

	public static void save(Object e, String name) {
		try {
			f = new File(name);

			f_out = new FileOutputStream(f);
			o_out = new ObjectOutputStream(f_out);

			o_out.writeObject(e);
			o_out.flush();
			f_out.close();
		}

		catch (FileNotFoundException ex) {
			try {
				if (f.createNewFile()) {
					f_out = new FileOutputStream(f);
					o_out = new ObjectOutputStream(f_out);

					o_out.writeObject(e);
					o_out.flush();
					f_out.close();
				}
				else {
					System.out.println("Failed to create a file.");
				}
			}
			catch (IOException ex2) { System.out.println("I/O Error occured."); }
		}

		catch (IOException ex3) { System.out.println("I/O Error occured."); }
	}
	public static boolean exists(String name) {
		File fi = new File(name);
		return (fi.isFile() && fi.exists());
	}

}
